package com.xwaf.platform.web.controller.auth;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xwaf.platform.common.api.CommonResponse;
import com.xwaf.platform.common.api.constants.BaseConstants;
import com.xwaf.platform.common.api.entity.ELUser;
import com.xwaf.platform.common.api.enums.DeviceType;
import com.xwaf.platform.common.utils.StringHelper;
import com.xwaf.platform.common.web.BaseController;
import com.xwaf.platform.system.api.constants.SysConfigConstant;
import com.xwaf.platform.system.api.entity.DataBase;
import com.xwaf.platform.system.api.entity.auth.User;
import com.xwaf.platform.system.api.request.auth.UpdatePwdRequest;
import com.xwaf.platform.system.api.service.auth.UserService;
import com.xwaf.platform.system.api.service.gateway.TokenService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 用户表
 * <p>
 * 
 * @author 李聪 <br>
 * @email xwaf_love@yeah.net <br>
 * @since JDK 1.8<br>
 * @date 2019-5-25 12:21:34 <br>
 * @see 无<br>
 *      Copyright (c) 2019, xwaf_love@yeah.net All Rights Reserved.<br>
 */
@RestController
@Api(tags = "用户")
@RequestMapping(value = "/m/user/")
public class UserController extends BaseController {

	@Autowired
	private TokenService tokenService;

	@Autowired
	private UserService userService;

	@ApiOperation(value = "分页查询", response = User.class)
	@PostMapping(value = "page", produces = "application/json;charset=UTF-8")
	public CommonResponse page(@RequestParam("currentPage") String currentPage,
			@RequestParam("pageSize") String pageSize, @RequestBody User user) {
		CommonResponse resp = CommonResponse.createCommonResponse();
		if (!StringUtils.isNotBlank(currentPage) & !StringUtils.isNotBlank(pageSize)) {
			currentPage = "1";
			pageSize = "10";
		}
		Page<User> page = new Page<User>(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
		Page<User> result = userService.selPageList(page, user);
		resp.setData(result);
		return resp;
	}

	@ApiOperation(value = "根据条件查询用户表", notes = "根据条件查询用户表信息", httpMethod = "GET", response = User.class, produces = MediaType.APPLICATION_JSON_VALUE)
	@GetMapping(value = "users", produces = "application/json;charset=UTF-8")
	public CommonResponse list(@RequestParam("name") String name) {
		Wrapper<User> wrapper = new EntityWrapper<User>();
		wrapper.like("name", name);
		List<User> list = userService.selectList(wrapper);
		for (User u : list) {
			u.setPassword(null);
		}
		return CommonResponse.createCommonResponse(list);
	}

	@ApiOperation(value = "新增用户表", notes = "新增用户表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
	@PostMapping(value = "add", produces = "application/json;charset=UTF-8")
	public CommonResponse addUser(@RequestBody User user) {
		ELUser loginUser = getLoginUser();
		if (loginUser != null) {
			user.setCreateBy(loginUser.getId());
			user.setUpdateBy(loginUser.getId());
		}
		user.setId(DataBase.getDataBaseId(DataBase.UR));
		boolean isAdded = userService.insert(user);
		if (isAdded) {
			return CommonResponse.createCommonResponse(user);
		} else {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "新增失败!");
		}
	}

	@ApiOperation(value = "修改用户表", notes = "修改用户表信息", httpMethod = "PUT", produces = MediaType.APPLICATION_JSON_VALUE)
	@PutMapping(value = "update/{userId}", produces = "application/json;charset=UTF-8")
	public CommonResponse updateUser(@PathVariable("userId") String userId, @RequestBody User user) {
		ELUser loginUser = getLoginUser();
		if (loginUser != null) {
			user.setUpdateBy(loginUser.getId());
		}
		user.setId(userId);
		boolean isUpdated = userService.updateById(user);
		if (isUpdated) {
			return CommonResponse.createCommonResponse();
		} else {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "修改失败!");
		}
	}

	@ApiOperation(value = "删除用户表", notes = "删除用户表信息", httpMethod = "DELETE", produces = MediaType.APPLICATION_JSON_VALUE)
	@DeleteMapping(value = "delete/{userIds}", produces = "application/json;charset=UTF-8")
	public CommonResponse delById(@PathVariable("userIds") List<String> userIds) {
		// boolean isDel = userService.deleteBatchIds(userIds);
		boolean isDel = true;
		if (isDel) {
			return CommonResponse.createCommonResponse();
		} else {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "删除失败!");
		}
	}

	@ApiOperation(value = "查看用户表详情", notes = "查看用户表详情信息", httpMethod = "GET", response = User.class, produces = MediaType.APPLICATION_JSON_VALUE)
	@GetMapping(value = "info/{userId}", produces = "application/json;charset=UTF-8")
	public CommonResponse getInfoById(@PathVariable("userId") String userId) {
		User user = userService.selectById(userId);
		if (StringHelper.isNotEmpty(user)) {
			user.setPassword(null);
		}
		return CommonResponse.createCommonResponse(user);
	}

	@ApiOperation(value = "重置密码", response = User.class)
	@GetMapping(value = "/resetPassword/{userId}", produces = "application/json;charset=UTF-8")
	public CommonResponse resetPwd(@PathVariable("userId") String userId) {
		Wrapper<User> wrapper = new EntityWrapper<User>();
		wrapper.eq("id", userId);
		User user = userService.selectOne(wrapper);
		user.setPassword(new Sha256Hash("888888", SysConfigConstant.LOGIN_MD5_KEY).toHex());
		boolean isUpdate = userService.updateById(user);
		if (isUpdate) {
			// 重置密码成功 清空缓存
			tokenService.clearToken(DeviceType.PC.name(), userId);
			return CommonResponse.createCommonResponse();
		} else {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "重置密码失败");
		}
	}

	/**
	 * 
	 * <p>
	 * 修改员工密码
	 * <p>
	 * 
	 * @author 李聪 <br>
	 * @email xwaf_love@yeah.net <br>
	 * @since JDK 1.8<br>
	 * @date 2020年1月4日 上午11:36:58 <br>
	 * @see 无<br>
	 * @param session
	 * @param user
	 * @return
	 * @demo <br>
	 */
	@ApiOperation(value = "修改员工密码", response = User.class)
	@RequestMapping(value = "/changePassword", produces = "application/json;charset=utf-8")
	public CommonResponse changePassword(@RequestBody UpdatePwdRequest updatePwdRequest) {
		ELUser user = getLoginUser();
		String oldPassword = new Sha256Hash(updatePwdRequest.getOldPwd(), SysConfigConstant.LOGIN_MD5_KEY).toHex();
		String newPassword = new Sha256Hash(updatePwdRequest.getNewPwd(), SysConfigConstant.LOGIN_MD5_KEY).toHex();
		User u = userService.selectById(user.getId());
		if (!oldPassword.equals(u.getPassword())) {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "旧密码错误");
		}
		boolean bool = userService.updateUserPassword(newPassword, user);
		if (bool) {
			// 修改密码成功 清空缓存
			tokenService.clearToken(DeviceType.PC.name(), user.getId());
			return CommonResponse.createCommonResponse();
		} else {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "修改密码失败");
		}
	}
}
